<html>
<head>
<style>
span {padding: 3px; padding-left:10px;margin-left:0px;}
span:hover { color: #DF7A79;}
</style>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="chrome_ex_oauthsimple.js"></script>
<script type="text/javascript" src="chrome_ex_oauth.js"></script>
<script type="text/javascript" src="zoqui.js"></script>
<title>Contact Updater</title>
<script>
var background = chrome.extension.getBackgroundPage();
function updSignUpInfo(){
    if (background.contacts.isLogged()){
        $("#signup").text("Logout");
        $("#read").show("");
        $("#contactlist").html("");
    } else {
        $("#signup").text("Login");
        $("#read").hide("");
        $("#contactlist").html("");
        $('.contactid').die('click', function(el){});
    }
};

function init(){
    updSignUpInfo();
};

function authenticate(){
    background.contacts.authenticate(function(ret){
        if (ret) 
            updSignUpInfo();
    });
};

function readEntry(el){
    var readLink = $(el).find('input:eq(0)').val();
    var editLink = $(el).find('input:eq(1)').val();
    var etag = $(el).find('input:eq(2)').val();
    $("#entryid").val(editLink);
    $("#entryetag").val(etag);
    $("#entry").val('Please Wait');
    $('#result').text('');
    background.contacts.getEntry(unescape(readLink), function(ret){        
        $("#entry").val(ret);
    });
}

function saveEntry(){
    var url = unescape($('#entryid').val());
    var etag = unescape($('#entryetag').val());
    var body = $("#entry").val();
    background.contacts.putEntry(url, etag, body, function(ret){
        $("#result").val(ret);
    });    
}

function jsonTests()
{
    var jsontxt = '{ \
        "appointments" : [\
            {"email": "1@example.com", "when": "1994-11-05T08:15:30-03:00", "status": "0"},\
            {"email": "2@example.com", "when": "1994-11-05T09:15:30-03:00", "status": "1"},\
            {"email": "3@example.com", "when": "1994-11-05T10:15:30-03:00", "status": "2"},\
            {"email": "4@example.com", "when": "1994-11-05T11:15:30-03:00", "status": "3"}\
        ]\
    }';
    
    var json=JSON.parse(jsontxt);       
    json['appointments'].splice(1,1); // remove the second element
    var jsonstring = JSON.stringify(json);  
    alert(jsontxt + '\n\n' + jsonstring);
}
function jsontest2(){
    var jsontxt = '{&quot;appointments&quot;:[{&quot;email&quot;:&quot;1@example.com&quot;,&quot;when&quot;:&quot;1994-11-05T08:15:30-03:00&quot;,&quot;status&quot;:&quot;0&quot;},{&quot;email&quot;:&quot;3@example.com&quot;,&quot;when&quot;:&quot;1994-11-05T10:15:30-03:00&quot;,&quot;status&quot;:&quot;2&quot;},{&quot;email&quot;:&quot;4@example.com&quot;,&quot;when&quot;:&quot;1994-11-05T11:15:30-03:00&quot;,&quot;status&quot;:&quot;3&quot;}]}'; 
    var jsontxt = $("<div/>").html(jsontxt).text();   
    var json=JSON.parse(jsontxt);
    var jsonstring = JSON.stringify(json);  
}

function ReadSave(el){
    var readLink = $(el).find('input:eq(0)').val();
    var con2 = new zoqui.GContacts('Contacts Updater',readLink);
    con2.get(function(ret){
        if (ret){
            var json = con2.extendedPropertyJSON('field1');
            if (json){
                var email = json['appointments'][0]['email'];
            }
            else{
                json = {};
                json['appointments'] = [];
                json['appointments'].push({});
                json['appointments'][0]['email']='marco@zoqui.com';
                json['appointments'][0]['when']='1994-11-05T09:15:30-03:00';
                json['appointments'][0]['status']='0';
                con2.extendedPropertyJSON('field1',json);
            }
            con2.put(function(ret){
                if (ret)
                    $("#result").val(con2.lastUpdate);
            });
        }
    }); 
}

/*
example
<?xml version='1.0' encoding='UTF-8'?>
<entry xmlns='http://www.w3.org/2005/Atom' xmlns:gContact='http://schemas.google.com/contact/2008' xmlns:batch='http://schemas.google.com/gdata/batch' xmlns:gd='http://schemas.google.com/g/2005' gd:etag='&quot;Q3oyejVSLyt7ImA9WxFSEE8LTgw.&quot;'>
    <id>http://www.google.com/m8/feeds/contacts/marco%40zoqui.com/base/1d29aa70818c0e1</id>
    <updated>2010-04-11T21:39:42.492Z</updated>
    <app:edited xmlns:app='http://www.w3.org/2007/app'>2010-04-11T21:39:42.492Z</app:edited>
    <category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/contact/2008#contact'/>
    <title>Jose Luis Vigiarelli - Pintor</title>
    <content>Notes: Tinta 18l Gelo Fosco Acrilico 
    Massa Corrida 3,6l
    Lixa 220 - 2 folhas
    Fita para cobrir rodape daquele piso
    Mao de obra 350</content>
    <link rel='http://schemas.google.com/contacts/2008/rel#photo' type='image/*' href='http://www.google.com/m8/feeds/photos/media/marco%40zoqui.com/1d29aa70818c0e1'/>
    <link rel='self' type='application/atom+xml' href='http://www.google.com/m8/feeds/contacts/marco%40zoqui.com/full/1d29aa70818c0e1'/>
    <link rel='edit' type='application/atom+xml' href='http://www.google.com/m8/feeds/contacts/marco%40zoqui.com/full/1d29aa70818c0e1'/>
    <gd:name>
    <gd:fullName>Jose Luis Vigiarelli - Pintor</gd:fullName>
    <gd:givenName>Jose</gd:givenName>
    <gd:additionalName>Luis</gd:additionalName>
    <gd:familyName>Vigiarelli - Pintor</gd:familyName>
    </gd:name>
    <gd:phoneNumber rel='http://schemas.google.com/g/2005#work'>"32331808</gd:phoneNumber>
    <gd:extendedProperty name='field1' value='value666'/>
    <gContact:groupMembershipInfo deleted='false' href='http://www.google.com/m8/feeds/groups/marco%40zoqui.com/base/6'/>
</entry>
*/
function saveProgramatically(){
    var text = $("#entry").val();
    var parser=new DOMParser();
    var xml = parser.parseFromString(text,"text/xml");
    var name = $(xml).find("title").text();
    var readLink = $(xml).find("link[rel='self']").attr('href');
    var editLink = $(xml).find("link[rel='edit']").attr('href');
    var etag   = $(xml).find("entry").attr('gd:etag');
    var exProp = $(xml).find("[name='field1']");
    if (exProp[0]){
        var url = unescape(editLink);
        var etag = unescape(etag).replace(/"/g,'');     
        $(xml).find("entry").attr('gd:etag',etag);
        var newvalue = $('#newvalue').val();
        exProp.attr('value',newvalue);
        var xmlstring = (new XMLSerializer()).serializeToString(xml);
        //$("#result").val(xmlstring);        
        background.contacts.putEntry(url, etag, xmlstring, function(ret){
            $("#result").val(ret);
        });    
    }
}

function listAll(){   
    $('#contactlist').text("Please wait");
    $('#entryid').val('');
    $('#entryetag').val('');
    $("#entry").val('');
    background.contacts.get("https://www.google.com/m8/feeds/contacts/default/full", 10, function(jsonret){
        if (jsonret && jsonret['feed'] && jsonret.feed['entry']){
            var entry = null;
            $('#contactlist').text('');
            $('#result').text('');
            for (var i = 0; i<jsonret.feed.entry.length; i++) {
                entry = jsonret.feed.entry[i];
                var etag = entry['gd$etag'];
                var name = entry['title']['$t'];
                //var link = entry['id']['$t'];
                var editLink = '';
                var readLink = '';
                for (var j=0;j<entry['link'].length; j++){
                    if (readLink==='' && entry['link'][j]['rel']==='self'){
                        readLink=entry['link'][j]['href'];
                    }
                    if (editLink==='' && entry['link'][j]['rel']==='edit'){
                        editLink=entry['link'][j]['href'];
                    }
                    if (readLink!='' && editLink!='')
                        break;                    
                }
                var h1 = '<input type="hidden" value="'+readLink+'" name="readLink">';
                var h2 = '<input type="hidden" value="'+editLink+'" name="editLink">';
                var h3 = '<input type="hidden" value='+etag+' name="etag">';
                var rn = ' <span onclick="ReadSave(this);">ReadSave'+h1+'</span>';
                $('#contactlist').append('<li><span onclick="readEntry(this);">'+name+h1+h2+h3+'</span>'+rn+'</li>');
            }
        }
    });
};

</script>
</head>
<body onload="init()">
<h2>Contacts Entry updater</h2>
<span id="signup" onclick="authenticate();"></span>
<br>
<div style="position:absolute;left: 10px; height:600px;width:300px;border: 1px solid black;">
<span id="read" onclick="listAll();">Read</span><br>
<ol id="contactlist"></ol>
</div>
<div style="position:absolute;left: 320px; height:600px; width:700px;border: 1px solid black;">
Edit Link ID: <input id="entryid" value="" style="width:250px;">
Etag: <input id="entryetag" value="" style="width:250px;">
<textarea id='entry' cols='70' rows='33' style='margin-left:20px;width:95%;border: 0px;'></textarea><br>
<span id="save" onclick="saveEntry();">Save</span> | 
<span id="buildXMLDom" onclick="saveProgramatically();">Save Programatically:</span> <input id="newvalue" type="text" value=""><=Field1 Value
</div>
<div style="position:absolute;top:700px;left: 320px; height:600px; width:700px;border: 1px solid black;">
Save Response<br>
<textarea id='result' cols='70' rows='33' style='margin-left:20px;;width:95%;border: 0px;'></textarea>
</div>
<div style="position:absolute;top:700px;left: 10px; height:600px; width:300px;border: 1px solid black;padding:3px;">
<h3>Instructions</h3>
<ol>
	<li>Click on Login</li>
    <li>Click on Read</li>
    <li>Change Content</li>
    <li>Click on Save</li> 
</ol>
<br>
<h3>You notice that</h3>
<ul>
	<li>Extended Properties are not displayed at Contacts, but they are successfull retrieved</li>
    <li>Edit Link ID will change only if you save a modified content. In case you do not modify the content, the edit link returns the same as the last one</li>    
    <li>Custom Fields (gContact:userDefinedField) are visible at Contacts page</li>
    <li>Extended Properties (gd:extendedProperty) are not visible in Contacts page but they can be read/write using xml protocol</li> 
    <li>Due the eTag use, you can't save the same content twice. You need to read all before you be able to</li>
    
</ul>
</div>
</body>
</html>